interface IPageData {
  inputText: string;
  backgroundImage: string;
}

Page<IPageData>({
  data: {
    inputText: '',
    backgroundImage: '../../assets/default-bg.svg'
  },

  // 设置背景图片
  setBackground(type: string = '') {
    const imageName = type ? `${type}-bg.svg` : 'default-bg.svg';
    const fullPath = `${wx.env.USER_DATA_PATH}/${imageName}`;
    const fs = wx.getFileSystemManager();
    
    try {
      fs.copyFileSync(`/assets/${imageName}`, fullPath);
      this.setData({
        backgroundImage: fullPath
      });
    } catch (e) {
      console.error(`设置${type || '默认'}背景失败:`, e);
    }
  },

  onLoad() {
    // 页面加载时初始化
    this.setBackground();
  },

  onTextInput(e: WechatMiniprogram.Input) {
    const text = e.detail.value;
    this.setData({
      inputText: text
    });
    
    // 根据输入文本分析关键词
    this.matchBackground(text);
  },

  matchBackground(text: string) {
    // 简单的关键词匹配逻辑
    const foodKeywords = ['美食', '食物', '好吃', '美味', '餐厅', '菜'];
    const sceneryKeywords = ['风景', '旅游', '景点', '自然', '美景'];
    
    let matchedType = '';
    
    if (foodKeywords.some(keyword => text.includes(keyword))) {
      matchedType = 'food';
    } else if (sceneryKeywords.some(keyword => text.includes(keyword))) {
      matchedType = 'scenery';
    }
    
    // 根据匹配类型设置背景
      switch (matchedType) {
        case 'food':
          this.setBackground('food');
          break;
        case 'scenery':
          this.setBackground('scenery');
          break;
        default:
          // 保持默认背景
          break;
    }
  },

  async saveImage() {
    wx.showToast({
      title: '图片生成中...',
      icon: 'loading'
    });

    try {
      // 创建画布上下文
      const ctx = wx.createCanvasContext('imageCanvas');
      const width = 300;
      const height = 400;

      // 创建渐变背景
      const gradient = ctx.createLinearGradient(0, 0, width, height);
      let startColor = '#ff9a9e';
      let endColor = '#fad0c4';

      // 根据当前背景类型设置渐变颜色
      if (this.data.backgroundImage.includes('food')) {
        startColor = '#ffd1a1';
        endColor = '#ffaa6c';
      } else if (this.data.backgroundImage.includes('scenery')) {
        startColor = '#89f7fe';
        endColor = '#66a6ff';
      }

      gradient.addColorStop(0, startColor);
      gradient.addColorStop(1, endColor);

      // 绘制渐变背景
      ctx.setFillStyle(gradient);
      ctx.fillRect(0, 0, width, height);

      // 绘制装饰图案
      ctx.setFillStyle('rgba(255,255,255,0.1)');
      ctx.beginPath();
      ctx.moveTo(0, 100);
      for (let x = 0; x <= width; x += 50) {
        const y = 100 + Math.sin((x / width) * Math.PI) * 20;
        ctx.lineTo(x, y);
      }
      ctx.lineTo(width, height);
      ctx.lineTo(0, height);
      ctx.closePath();
      ctx.fill();

      // 设置文字样式
      ctx.setFillStyle('#4a90e2');
      ctx.setFontSize(50); // 调整字号为更合适的50px
      ctx.setTextBaseline('top');
      ctx.setTextAlign('left');
      
      // 计算文字位置和边距
      const margin = width * 0.1; // 减少边距至10%
      const topPosition = height * 0.2; // 调整顶部位置至20%
      const maxWidth = width - margin * 2; // 文字最大宽度
      const lineHeight = 60; // 调整行高为字体大小的1.2倍
      
      // 增强文字阴影效果
      ctx.setShadow(2, 2, 4, 'rgba(0,0,0,0.3)');
      
      // 文字自动换行处理
      const text = this.data.inputText;
      let lines = [];
      let currentLine = '';
      
      // 首先计算所有行
      for (let i = 0; i < text.length; i++) {
        const char = text[i];
        const tempLine = currentLine + char;
        const metrics = ctx.measureText(tempLine);
        
        if (metrics.width > maxWidth && currentLine) {
          lines.push(currentLine);
          currentLine = char;
        } else {
          currentLine = tempLine;
        }
      }
      
      // 添加最后一行
      if (currentLine) {
        lines.push(currentLine);
      }
      
      // 绘制所有行
      let y = topPosition;
      lines.forEach(line => {
        ctx.fillText(line, margin, y);
        y += lineHeight;
      });

      // 绘制完成
      await new Promise((resolve) => {
        ctx.draw(false, () => resolve(null));
      });

      // 将画布内容转换为临时文件
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.canvasToTempFilePath({
          canvasId: 'imageCanvas',
          success: res => resolve(res.tempFilePath),
          fail: err => reject(err)
        });
      });

      // 保存图片到相册
      await wx.saveImageToPhotosAlbum({
        filePath: tempFilePath
      });

      wx.showToast({
        title: '保存成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('保存图片失败:', error);
      wx.showToast({
        title: '保存失败',
        icon: 'error'
      });
    }
  }
});